package com.mark.controller.portal;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.google.common.collect.Maps;
import com.mark.common.ServerResponse;
import com.mark.controller.common.CurrentUser;
import com.mark.enums.PayEnum;
import com.mark.pojo.User;
import com.mark.service.IPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by Choisaaaa on 2018/4/25.
 * 调用支付宝的controller
 */

@Controller
@RequestMapping("/pay/")
@Slf4j
public class PayController {
    @Autowired
    private IPayService iPayService;

    @RequestMapping("pay")
    @ResponseBody
    public ServerResponse pay(HttpServletRequest httpServletRequest, String orderNo, HttpServletRequest request){
        ServerResponse response = CurrentUser.getCurrentUser(httpServletRequest);
        if (!response.isSuccess()){
            return response;
        }
        User currentUser = (User) response.getData();
        String path = request.getSession().getServletContext().getRealPath("upload");
        return  iPayService.pay(orderNo,currentUser.getId(),path);
    }

    //返回的是一个字符串
    @RequestMapping("alipay_callback.do")
    @ResponseBody
    public Object alipayCallback(HttpServletRequest request){
        Map<String,String> params = Maps.newHashMap();
        Map requestParams = request.getParameterMap();
        for(Iterator iter = requestParams.keySet().iterator(); iter.hasNext();){
            String name = (String)iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for(int i = 0 ; i <values.length;i++){

                valueStr = (i == values.length -1)?valueStr + values[i]:valueStr + values[i]+",";
            }
            params.put(name,valueStr);
        }
        log.info("支付宝回调,sign:{},trade_status:{},参数:{}",params.get("sign"),params.get("trade_status"),params.toString());

        //非常重要,验证回调的正确性,是不是支付宝发的.并且呢还要避免重复通知.
        params.remove("sign_type");
        try {
            boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, Configs.getAlipayPublicKey(),"utf-8",Configs.getSignType());

            if(!alipayRSACheckedV2){
                return ServerResponse.createByErrorMessage("非法请求,验证不通过,再恶意请求我就报警找网警了");
            }
        } catch (AlipayApiException e) {
            log.error("支付宝验证回调异常",e);
        }
        ServerResponse serverResponse = iPayService.aliCallback(params);
        if(serverResponse.isSuccess()){//如果是成功的话
            return PayEnum.RESPONSE_SUCCESS.getResponseInfo();
        }
        return PayEnum.RESPONSE_FAILED.getResponseInfo();
    }


    //检查是否付款成功
    @RequestMapping("query_order_pay_status.do")
    @ResponseBody
    public ServerResponse<Boolean> queryOrderPayStatus(HttpServletRequest httpServletRequest, String orderNo){

        ServerResponse response = CurrentUser.getCurrentUser(httpServletRequest);
        if (!response.isSuccess()){
            return response;
        }
        User currentUser = (User) response.getData();
        ServerResponse serverResponse = iPayService.queryOrderPayStatus(currentUser.getId(),orderNo);
        if(serverResponse.isSuccess()){
            return ServerResponse.createBySuccess(true);
        }
        return ServerResponse.createBySuccess(false);
    }

}
